const redis = require("redis");
const RedisConfig = require("$config/redis.config");
const AppConfig = require("$config/app.config");
const stringUtil = require('@/utils/string.util');

/**
 * Redis 客户端
 */
class RedisClient {
	constructor() {
		// 创建 Redis 客户端
		this.client = redis.createClient(RedisConfig.PORT, RedisConfig.HOST);
		// 身份认证
		this.client.auth(RedisConfig.PASSWORD, function (error) {
			if (error) {
				return console.error("Redis Authentication Failed:", error);
			}
			console.log("Redis Authenticated");
		});

		// 监听连接错误
		this.client.on("error", err => {
			console.error("Redis error:", err);
		});

		// 监听连接成功
		this.client.on("connect", () => {
			console.log("Connected to Redis");
		});
	}

	/**
	 * 获取key
	 */
	_getKey(key) {
		return `${AppConfig.REDIS_KEY_PREFIX}:${key}`;
	}

	/**
	 * 设置键值对
	 * @param {string} key - 键名
	 * @param {string} value - 值
	 * @param {number} [expire] - 过期时间（秒）
	 * @returns {Promise<void>}
	 */
	async set(key, value, expire) {
		return new Promise((resolve, reject) => {
			key = this._getKey(key);
			value = typeof value === "string" ? value : JSON.stringify(value);
			this.client.set(key, value, err => {
				if (err) {
					return reject(err);
				}
				if (expire) {
					this.client.expire(key, expire, err => {
						err ? reject(err) : resolve();
					});
					return;
				}
				resolve();
				console.log(`redis set [${key}] successful!`);
			});
		});
	}

	/**
	 * 获取键的值
	 * @param {string} key - 键名
	 * @returns {Promise<string|null>}
	 */
	async get(key) {
		return new Promise((resolve, reject) => {
			key = this._getKey(key);
			this.client.get(key, (err, reply) => {
				if (err) {
					return reject(err);
				}
				const content = stringUtil.isJsonString(reply) ? JSON.parse(reply) : reply;
				resolve(content);
			});
		});
	}

	/**
	 * 删除键
	 * @param {string} key - 键名
	 * @returns {Promise<void>}
	 */
	async del(key) {
		return new Promise((resolve, reject) => {
			key = this._getKey(key);
			this.client.del(key, err => {
				if (err) {
					reject(err);
				} else {
					resolve();
				}
			});
		});
	}

	/**
	 * 关闭 Redis 连接
	 */
	quit() {
		this.client.quit();
	}
}

// 导出 RedisClient 类
module.exports = new RedisClient();
